from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config

# 初始化数据库
db = SQLAlchemy()

def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    # 初始化扩展
    db.init_app(app)

    # 注册蓝图
    from app.routes.auth import auth_bp
    from app.routes.admin import admin_bp

    app.register_blueprint(auth_bp)
    app.register_blueprint(admin_bp)

    # 创建数据库表
    with app.app_context():
        db.create_all()
        # 创建超级管理员
        from app.models.user import User
        from app.models.role import Role
        admin_role = Role.query.filter_by(name='admin').first()
        if not admin_role:
            admin_role = Role(name='admin', description='超级管理员')
            db.session.add(admin_role)
            db.session.commit()

        admin_user = User.query.filter_by(username=app.config['ADMIN_USERNAME']).first()
        if not admin_user:
            admin_user = User(username=app.config['ADMIN_USERNAME'],
                              password=app.config['ADMIN_PASSWORD'],
                              role_id=admin_role.id)
            db.session.add(admin_user)
            db.session.commit()

    return app